package com.ruoyi.safe.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.config.MinIoProperties;
import com.ruoyi.common.core.domain.entity.ListType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.MinIoUtil;
import com.ruoyi.safe.constant.ListTypeConstants;
import com.ruoyi.safe.domain.*;
import com.ruoyi.safe.domain.dto.ProjectCheckRecordPhotonAlbumDTO;
import com.ruoyi.safe.domain.dto.UserSearchDTO;
import com.ruoyi.safe.domain.vo.BizSafeAttachBizInfo;
import com.ruoyi.safe.domain.vo.CommonUserVO;
import com.ruoyi.safe.mapper.*;
import com.ruoyi.safe.service.*;
import io.minio.MinioProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 安全相册Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-20
 */
@Service
public class BizSafeAttachServiceImpl implements IBizSafeAttachService {
    @Autowired
    BizSafeAttachMapper bizSafeAttachMapper;
    @Autowired
    MinIoProperties minIoProperties;
    @Autowired
    BizDutyRegionMapper bizDutyRegionMapper;
    @Autowired
    IBizDutyRegionService bizDutyRegionService;
    @Autowired
    CommonProjectMapper commonProjectMapper;
    @Autowired
    CommonUserMapper commonUserMapper;
    @Autowired
    BizProjectCheckRecordMapper  bizProjectCheckRecordMapper;
    @Autowired
    IBizProjectCheckRecordService bizProjectCheckRecordService;
    @Autowired
    ListConstructionMapper listConstructionMapper;
    @Autowired
    ListDeviseMapper listDeviseMapper;
    @Autowired
    ListMaintenanceMapper listMaintenanceMapper;
    @Autowired
    ListManageMapper listManageMapper;
    @Autowired
    ListTypeMapper listTypeMapper;
    /**
     * 查询安全相册
     *
     * @param id 安全相册主键
     * @return 安全相册
     */
    @Override
    public BizSafeAttach selectBizSafeAttachById(Long id) {
        BizSafeAttach bizSafeAttach =  bizSafeAttachMapper.selectBizSafeAttachById(id);
        if(bizSafeAttach == null){
            throw new ServiceException("没有对应的安全附件");
        }
        BizProjectCheckRecord bizProjectCheckRecord = bizProjectCheckRecordMapper.selectBizProjectCheckRecordById(bizSafeAttach.getBizId());
        ListType listType = null;
        if(StringUtils.isEmpty(bizProjectCheckRecord.getTypeNo())){
            throw new ServiceException("隐患记录没有设置的清单类型");
        }else{
            listType  = listTypeMapper.selectListTypeById(Long.valueOf(bizProjectCheckRecord.getTypeNo()));
            if(listType == null){
                throw new ServiceException("隐患记录没有对应的清单类型");
            }
        }
        //隐患性质
        String dangerLevel = "";
        //判断清单类型
        if(listType.getTypeNo().startsWith(ListTypeConstants.DEVISE)){
            //设计清单
            ListDevise listDevise = listDeviseMapper.selectListDeviseById(bizProjectCheckRecord.getListId());
            if(listDevise == null){
                throw new ServiceException("没有相对应的设计清单");
            }
            dangerLevel = listDevise.getDangerLevel();
        }else  if(listType.getTypeNo().startsWith(ListTypeConstants.CONSTRUCTION)){
            //设计清单
            ListConstruction listConstruction = listConstructionMapper.selectListConstructionById(bizProjectCheckRecord.getListId());
            if(listConstruction == null){
                throw new ServiceException("没有相对应的施工清单");
            }
            dangerLevel = listConstruction.getDangerLevel();
        }else  if(listType.getTypeNo().startsWith(ListTypeConstants.MAINTENANCE)){
            //养护清单
            ListMaintenance listMaintenance = listMaintenanceMapper.selectListMaintenanceById(bizProjectCheckRecord.getListId());
            if(listMaintenance == null){
                throw new ServiceException("没有相对应的养护清单");
            }
            dangerLevel = listMaintenance.getDangerLevel();
        }else  if(listType.getTypeNo().startsWith(ListTypeConstants.MANAGE)){
            //管理清单
            ListManage listManage = listManageMapper.selectListManageById(bizProjectCheckRecord.getListId());
            if(listManage == null){
                throw new ServiceException("没有相对应的管理清单");
            }
            dangerLevel = listManage.getDangerLevel();
        }else{
            throw new ServiceException("没有相对应的清单");
        }
        String dangerLevelLabel = DictUtils.getDictLabel("list_danger_level",dangerLevel);
        //区域
        Long dutyAreaId = Long.valueOf(bizProjectCheckRecord.getDutyArea());
        BizDutyRegion bizDutyRegion = bizDutyRegionMapper.selectBizDutyRegionById(dutyAreaId);
        //项目
        CommonProject commonProject = commonProjectMapper.selectCommonProjectById(bizProjectCheckRecord.getProjectId());
        //上传人
        UserSearchDTO commonUserDTO = new UserSearchDTO();
        commonUserDTO.setUserName(bizSafeAttach.getCreateBy());
        List<CommonUserVO> commonUserVOList = commonUserMapper.selectCommonUserList(commonUserDTO);
        if(commonUserVOList.size() == 0) {
            throw new ServiceException("没有对应的上传人");
        }
        CommonUserVO commonUserVO = commonUserVOList.get(0);
        //完善信息
        BizSafeAttachBizInfo bizSafeAttachBizInfo = new BizSafeAttachBizInfo();
        bizSafeAttachBizInfo.setProjectId(commonProject.getId());
        bizSafeAttachBizInfo.setProjectName(commonProject.getName());
        bizSafeAttachBizInfo.setCheckSource(bizProjectCheckRecord.getCheckSource());
        bizSafeAttachBizInfo.setHiddenDangerStatus(bizProjectCheckRecord.getHiddenDangerStatus());
        bizSafeAttachBizInfo.setDangerLevel(dangerLevel);
        bizSafeAttachBizInfo.setDangerLevelName(dangerLevelLabel);
        bizSafeAttachBizInfo.setDutyArea(bizDutyRegion.getId());
        bizSafeAttachBizInfo.setDutyAreaName(bizDutyRegion.getRegionName());
        bizSafeAttachBizInfo.setBizId(bizProjectCheckRecord.getId());
        bizSafeAttachBizInfo.setTypeId(listType.getId());
        List<ListType> listTypes = listTypeMapper.selectListTypeListByTypeNos(listType.getAncestors().split(","));
        String typeName = listTypes.stream().map(item->item.getTypeName()).collect(Collectors.joining("/"));
        bizSafeAttachBizInfo.setTypeName(typeName);
        bizSafeAttachBizInfo.setFileName(bizSafeAttach.getName());
        bizSafeAttachBizInfo.setUploadUserName(bizSafeAttach.getCreateBy());
        bizSafeAttachBizInfo.setUploadNickName(commonUserVO.getNickName());
        bizSafeAttachBizInfo.setUploadTime(bizSafeAttach.getCreateTime());
        bizSafeAttach.setBizSafeAttachBizInfo(bizSafeAttachBizInfo);
        return bizSafeAttach;
    }

    @Override
    public List<BizProjectCheckRecord> selectBizProjectCheckRecordList(ProjectCheckRecordPhotonAlbumDTO projectCheckRecordPhotonAlbumDTO) {
        //查询检查区域
        List<String> dutyAreaIdChars = new ArrayList<>();;
        List<Long> dutyAreaIdList = projectCheckRecordPhotonAlbumDTO.getDutyAreaIds();
        if(dutyAreaIdList != null){
            for (int i = 0; i < dutyAreaIdList.size(); i++) {
                Long[] dutyAreaIds = bizDutyRegionService.selectSelfAndChildrenBizDutyRegionIdsById(dutyAreaIdList.get(i));
                dutyAreaIdChars.addAll(Arrays.stream(dutyAreaIds).map(item->String.valueOf(item)).collect(Collectors.toList()));
            }
            if(dutyAreaIdChars.size() == 0){
                return new ArrayList<>();
            }
        }

        //根据 隐患等级 查询符合条件的清单
        String dangerLevel = projectCheckRecordPhotonAlbumDTO.getDangerLevel();
        List<Long> listIds = null;
        if(dangerLevel != null){
            listIds = new ArrayList<>();
            //各种符合条件的清单id集合 list_construction list_devise list_maintenance list_manage
            ListConstruction listConstruction =  new ListConstruction();
            listConstruction.setDangerLevel(dangerLevel);
            listIds.addAll(listConstructionMapper.selectListConstructionList(listConstruction).stream().map(item->item.getId()).collect(Collectors.toList()));
            ListDevise listDevise = new ListDevise();
            listDevise.setDangerLevel(dangerLevel);
            listIds.addAll(listDeviseMapper.selectListDeviseList(listDevise).stream().map(item->item.getId()).collect(Collectors.toList()));
            ListMaintenance listMaintenance = new ListMaintenance();
            listMaintenance.setDangerLevel(dangerLevel);
            listIds.addAll(listMaintenanceMapper.selectListMaintenanceList(listMaintenance).stream().map(item->item.getId()).collect(Collectors.toList()));
            ListManage listManage = new ListManage();
            listManage.setDangerLevel(dangerLevel);
            listIds.addAll(listManageMapper.selectListManageList(listManage).stream().map(item->item.getId()).collect(Collectors.toList()));
        }
        //查询记录
        BizProjectCheckRecord bizProjectCheckRecord = new BizProjectCheckRecord();
        //项目id
        bizProjectCheckRecord.setProjectId(projectCheckRecordPhotonAlbumDTO.getProjectId());
        //检查来源
        bizProjectCheckRecord.setCheckSource(projectCheckRecordPhotonAlbumDTO.getCheckSource());
        //记录类型
        bizProjectCheckRecord.setRecordType(projectCheckRecordPhotonAlbumDTO.getRecordType());
        //检查区域
        bizProjectCheckRecord.setDutyAreas(dutyAreaIdChars);
        //清单列表
        bizProjectCheckRecord.setListIds(listIds);
        List<BizProjectCheckRecord> bizProjectCheckRecords = bizProjectCheckRecordService.selectBizProjectCheckRecordList(bizProjectCheckRecord);
        return bizProjectCheckRecords;
    }

    /**
     * 查询安全相册列表
     *
     * @param bizSafeAttach 安全相册
     * @return 安全相册
     */
    @Override
    public List<BizSafeAttach> selectBizSafeAttachList(BizSafeAttach bizSafeAttach) {
        List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachList(bizSafeAttach);
        bizSafeAttaches.forEach(item->{
            item.setUrl(MinIoUtil.getFileUrl(minIoProperties.getBucketName(),item.getName()));
            item.setFileId(String.valueOf(item.getId()));
        });
        return bizSafeAttaches;
    }

    /**
     * 查询安全相册列表
     *
     * @param bizSafeAttach 安全相册
     * @return 安全相册
     */
    @Override
    public List<BizSafeAttach> selectBizSafeAttachListIds(BizSafeAttach bizSafeAttach) {
        List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachListIds(bizSafeAttach);
        bizSafeAttaches.forEach(item->{
            item.setUrl(MinIoUtil.getFileUrl(minIoProperties.getBucketName(),item.getName()));
            item.setFileId(String.valueOf(item.getId()));
        });
        return bizSafeAttaches;
    }

    /**
     * 查询安全相册列表
     *
     * @param bizSafeAttach 安全相册
     * @return 安全相册
     */
    @Override
    public List<BizSafeAttach> selectBizSafeAttachListAlbum(BizSafeAttach bizSafeAttach) {
        List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachListAlbum(bizSafeAttach);
        bizSafeAttaches.forEach(item->{
            item.setUrl(MinIoUtil.getFileUrl(minIoProperties.getBucketName(),item.getName()));
            item.setFileId(String.valueOf(item.getId()));
        });
        return bizSafeAttaches;
    }

    /**
     * 新增安全相册
     *
     * @param bizSafeAttach 安全相册
     * @return 结果
     */
    @Override
    public int insertBizSafeAttach(BizSafeAttach bizSafeAttach) {
        bizSafeAttach.setCreateTime(DateUtils.getNowDate());
        bizSafeAttach.setCreateBy(SecurityUtils.getUsername());
        return bizSafeAttachMapper.insertBizSafeAttach(bizSafeAttach);
    }

    /**
     * 新增安全相册(未登录）
     *
     * @param bizSafeAttach 安全相册
     * @return 结果
     */
    @Override
    public int insertBizSafeAttachNoLogin(BizSafeAttach bizSafeAttach) {
        bizSafeAttach.setCreateTime(DateUtils.getNowDate());
        return bizSafeAttachMapper.insertBizSafeAttach(bizSafeAttach);
    }

    /**
     * 修改安全相册
     *
     * @param bizSafeAttach 安全相册
     * @return 结果
     */
    @Override
    public int updateBizSafeAttach(BizSafeAttach bizSafeAttach) {
        bizSafeAttach.setUpdateTime(DateUtils.getNowDate());
        bizSafeAttach.setUpdateBy(SecurityUtils.getUsername());
        return bizSafeAttachMapper.updateBizSafeAttach(bizSafeAttach);
    }

    /**
     * 批量删除安全相册
     *
     * @param ids 需要删除的安全相册主键
     * @return 结果
     */
    @Override
    public int deleteBizSafeAttachByIds(Long[] ids) {
        return bizSafeAttachMapper.deleteBizSafeAttachByIds(ids);
    }

    /**
     * 删除安全相册信息
     *
     * @param id 安全相册主键
     * @return 结果
     */
    @Override
    public int deleteBizSafeAttachById(Long id) {
        return bizSafeAttachMapper.deleteBizSafeAttachById(id);
    }


    /**
     * 批量通过文件名修改安全相册
     */
    @Override
    public int updateBizSafeAttachByBizId(String fileName, Long bizId) {
        if (StringUtils.isNotBlank(fileName)) {

            String[] split = fileName.split(",");
            List<String> list = Arrays.asList(split);
            /*优先将所有关联id全部清除，然后从新更新*/
            bizSafeAttachMapper.clearBizSafeAttachByBizId(bizId);
            List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachByFileNames(list);
            bizSafeAttaches.forEach(bizSafeAttach -> {
                //设置bizId
                bizSafeAttach.setBizId(bizId);
                bizSafeAttachMapper.updateBizSafeAttach(bizSafeAttach);
            });
            return 1;
        }
        return 0;
    }

    @Override
    public List<BizSafeAttach> selectBizSafeAttachByBizIds(Long[] bizIds) {
        Set<Long> set = new HashSet<>();
        for (long num : bizIds) {
            set.add(num);
        }
        return bizSafeAttachMapper.selectBizSafeAttachByBizIds(set);
    }

    /**
     * 批量通过文件名查询安全相册
     */
    @Override
    public Boolean selectBizSafeAttachByNames(String fileName, Long snowflakeNextId) {
        if (StringUtils.isNotBlank(fileName)) {

            String[] split = fileName.split(",");
            List<String> list = Arrays.asList(split);
            List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachByFileNames(list);
            bizSafeAttaches.forEach(bizSafeAttach -> {
                //设置bizId
                bizSafeAttach.setBizId(snowflakeNextId);
                bizSafeAttachMapper.updateBizSafeAttach(bizSafeAttach);
            });
            return true;
        }
        return false;
    }
}
